package com.xbongbong.paas.service.team.strategy;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.service.CustomerRuleService;
import com.xbongbong.paas.service.TransferBackRuleScriptService;
import com.xbongbong.paas.service.dynamic.crm.strategy.DynamicStrategyFactory;
import com.xbongbong.paas.service.dynamic.crm.strategy.TeamDynamicStrategy;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CloneUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.parent.interfaces.TeamStrategy;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailEditLabelDTO;
import com.xbongbong.pro.detailtab.dto.team.TeamDetailUpdateDTO;
import com.xbongbong.pro.detailtab.vo.team.TeamDetailEditCoPerVO;
import com.xbongbong.pro.detailtab.vo.team.TeamDetailEditLabelVO;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicTeamLabelDTO;
import com.xbongbong.pro.dynamic.pojo.dto.DynamicTeamUpdateDTO;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.UserTeamErrorCodeEnum;
import com.xbongbong.pro.enums.teammembers.enums.CoUserPermissionEnum;
import com.xbongbong.pro.enums.teammembers.enums.FormCoUserDefaultPermissionEnum;
import com.xbongbong.pro.listbatch.pojo.TeamBatchPojo;
import com.xbongbong.pro.team.TeamAfterFormatDTO;
import com.xbongbong.pro.team.TeamAfterVerifyDTO;
import com.xbongbong.pro.team.TeamVerifyDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ListBatchConstant;
import com.xbongbong.saas.constant.teammembers.TeamMembersConstant;
import com.xbongbong.saas.domain.entity.CustomerUserEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.enums.CustomerRuleEnum;
import com.xbongbong.saas.enums.UserTeamOperateTagEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.model.CustomerFocusModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.CustomerUserModel;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.service.impl.ListBatchServiceImpl;
import com.xbongbong.saas.service.toolbox.help.UserTeamHelp;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * 客户团队 策略实现
 * @author 魏荣杰
 *
 */
@Service
@Slf4j
public class CustomerTeamStrategy extends AbstractTeamStrategy implements TeamStrategy {

    @Resource
    private CustomerUserModel customerUserModel;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private CustomerRuleService customerRuleService;
    @Resource
    private UserModel userModel;
    @Resource
    private CustomerFocusModel customerFocusModel;
    @Resource
    private ListBatchServiceImpl listBatchService;
    @Resource
    private UserTeamHelp userTeamHelp;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private IndexTypeModel indexTypeModel;
    @Resource
    private TransferBackRuleScriptService transferBackRuleScriptService;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private DynamicStrategyFactory dynamicStrategyFactory;


    @Override
    public List<Integer> type() {
        return Collections.singletonList(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
    }

    @Override
    public TeamAfterVerifyDTO verify(TeamVerifyDTO teamVerifyDTO) throws XbbException {
        // 校验 和 封装
        return super.verifyTeam(teamVerifyDTO);
    }

    @Override
    public TeamAfterVerifyDTO specialVerify(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException {
        String corpid = teamAfterVerifyDTO.getCorpid();
        Integer operateTag = teamAfterVerifyDTO.getOperateTag();
        if (Objects.equals(UserTeamOperateTagEnum.HANDOVER.getOperateTag(), operateTag)) {
            //移交的公海池校验
            checkHandleOverPublicRule(teamAfterVerifyDTO);
        }else {
            // 其它情况校验公海池规则（如新增负责人）
            if (!teamAfterVerifyDTO.getFromDetail() && teamAfterVerifyDTO.getAddMainUserMap().containsKey(null)) {
                Map<String, Set<String>> map = teamAfterVerifyDTO.getAddMainUserMap().entrySet().stream().collect(Collectors.toMap(v -> String.valueOf(teamAfterVerifyDTO.getDataId().get(0)), v -> v.getValue()));
                List<TeamBatchPojo> teamBatchPojos = checkPublicRule(corpid, teamAfterVerifyDTO.getDataId(), teamAfterVerifyDTO.getBusinessType(), map, operateTag, teamAfterVerifyDTO.getTeamBatchPojos(), teamAfterVerifyDTO.getFromDetail(),
                        teamAfterVerifyDTO.getIsNew());
                if (Objects.nonNull(teamAfterVerifyDTO.getTeamBatchPojos())) {
                    teamAfterVerifyDTO.getTeamBatchPojos().addAll(teamBatchPojos);
                } else {
                    teamAfterVerifyDTO.setTeamBatchPojos(teamBatchPojos);
                }
            } else {
                List<TeamBatchPojo> teamBatchPojos = checkPublicRule(corpid, teamAfterVerifyDTO.getDataId(), teamAfterVerifyDTO.getBusinessType(), teamAfterVerifyDTO.getAddMainUserMap(), operateTag, teamAfterVerifyDTO.getTeamBatchPojos(),
                        teamAfterVerifyDTO.getFromDetail(), teamAfterVerifyDTO.getIsNew());
                if (Objects.nonNull(teamAfterVerifyDTO.getTeamBatchPojos())) {
                    teamAfterVerifyDTO.getTeamBatchPojos().addAll(teamBatchPojos);
                } else {
                    teamAfterVerifyDTO.setTeamBatchPojos(teamBatchPojos);
                }
            }
        }

        return teamAfterVerifyDTO;
    }

    @Override
    public void save(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException {
        String corpid = teamAfterVerifyDTO.getCorpid();

        TeamAfterFormatDTO teamAfterFormatDTO = formatTeam(teamAfterVerifyDTO);

        LinkedHashMap<String, Integer> esWait = judgeTeamEsWait(teamAfterFormatDTO);

        for (Iterator<Map.Entry<String, Integer>> iterator = esWait.entrySet().iterator(); iterator.hasNext(); ) {
            Map.Entry<String, Integer> entry = iterator.next();
            boolean hasNext = iterator.hasNext();
            switch (entry.getKey()) {
                case TeamMembersConstant.ADD_USER:
                    List<UserTeamEntity> addUserTeamList = teamAfterFormatDTO.getAddUserTeamList();
                    if (CollectionsUtil.isNotEmpty(addUserTeamList)) {
                        List<CustomerUserEntity> customerUserEntityList = new ArrayList<>();
                        try {
                            BeanUtil.copyPropertiesList(addUserTeamList, customerUserEntityList, CustomerUserEntity.class, false);
                        } catch (Exception e) {
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                        }
                        if (hasNext) {
                            customerUserModel.insertBatch(customerUserEntityList, true);
                        } else {
                            customerUserModel.insertBatch(customerUserEntityList, false);
                        }
                    }
                    break;
                case TeamMembersConstant.DEL_USER:
                    List<UserTeamEntity> delUserTeamList = teamAfterFormatDTO.getDelUserTeamList();
                    if (CollectionsUtil.isNotEmpty(delUserTeamList)) {
                        List<Long> idIn = delUserTeamList.stream().map(UserTeamEntity::getId).collect(Collectors.toList());
                        if (hasNext) {
                            customerUserModel.batchUpdateByUserIdIn(corpid, idIn, delUserTeamList, null, DelEnum.DELETE.getDel(), WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        } else {
                            customerUserModel.batchUpdateByUserIdIn(corpid, idIn, delUserTeamList, null, DelEnum.DELETE.getDel(), WriteRequest.RefreshPolicy.NONE);
                        }
                        // 删除的要共享取关
                        List<String> useridIn = delUserTeamList.stream().map(UserTeamEntity::getUserId).collect(Collectors.toList());
                        delUserTeamList.forEach(v -> {
                            customerFocusModel.unFocusByUserIdIn( v.getDataId(), corpid, useridIn);
                        });

                    }
                    break;
                case TeamMembersConstant.TO_MAIN_USER:
                    List<UserTeamEntity> updateUserToMainTeamList = teamAfterFormatDTO.getUpdateUserToMainTeamList();
                    if (CollectionsUtil.isNotEmpty(updateUserToMainTeamList)) {
                        List<Long> idIn = updateUserToMainTeamList.stream().map(UserTeamEntity::getId).collect(Collectors.toList());
                        if (hasNext) {
                            customerUserModel.batchUpdateByUserIdIn(corpid, idIn, updateUserToMainTeamList, BasicConstant.MAIN_USER, DelEnum.NORMAL.getDel(), WriteRequest.RefreshPolicy.NONE);
                        } else {
                            customerUserModel.batchUpdateByUserIdIn(corpid, idIn, updateUserToMainTeamList, BasicConstant.MAIN_USER, DelEnum.NORMAL.getDel(), WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        }
                    }
                    break;
                case TeamMembersConstant.TO_CO_USER:
                    List<UserTeamEntity> updateUserToCoTeamList = teamAfterFormatDTO.getUpdateUserToCoTeamList();
                    if (CollectionsUtil.isNotEmpty(updateUserToCoTeamList)) {
                        List<Long> idIn = updateUserToCoTeamList.stream().map(UserTeamEntity::getId).collect(Collectors.toList());
                        if (hasNext) {
                            customerUserModel.batchUpdateCoAndPerByUserIdIn(corpid, idIn, updateUserToCoTeamList, BasicConstant.COOP_USER, false, WriteRequest.RefreshPolicy.NONE);
                        } else {
                            customerUserModel.batchUpdateCoAndPerByUserIdIn(corpid, idIn, updateUserToCoTeamList, BasicConstant.COOP_USER, false, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        }
                    }
                    break;
                case TeamMembersConstant.UPDATE_USER:
                    List<UserTeamEntity> updateUserTeamMainList = teamAfterFormatDTO.getUpdateUserTeamMainList();
                    if (CollectionsUtil.isNotEmpty(updateUserTeamMainList)) {
                        //这边需要更新团队成员的teamUserId，这个字段是不需要存数据库的，但是es还是需要更新一下更新时间
                        List<Long> idIn = updateUserTeamMainList.stream().map(UserTeamEntity::getId).collect(Collectors.toList());
                        if (hasNext) {
                            customerUserModel.batchUpdateTeamMainByUserIdIn(corpid, idIn, updateUserTeamMainList, WriteRequest.RefreshPolicy.NONE);
                        } else {
                            customerUserModel.batchUpdateTeamMainByUserIdIn(corpid, idIn, updateUserTeamMainList, WriteRequest.RefreshPolicy.WAIT_UNTIL);
                        }
                    }
                    break;
                default:
            }
        }
    }

    /**
     * 校验移交的公海池规则
     *
     * @param teamAfterVerifyDTO 经过上层校验得到的一个实体
     */
    private void checkHandleOverPublicRule(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException{
        List<TeamBatchPojo> teamBatchPojos = teamAfterVerifyDTO.getTeamBatchPojos();
        String corpid = teamAfterVerifyDTO.getCorpid();
        List<Long> dataIdList = teamAfterVerifyDTO.getDataId();
        List<Long> originalIdList = (List<Long>)CloneUtil.deepClone(dataIdList);
        String changeUserId = teamAfterVerifyDTO.getChangeUserId();
        Map<String, Set<String>> addMainUserMap = teamAfterVerifyDTO.getAddMainUserMap();
        Map<String, Set<String>> delMainUserMap = Objects.nonNull(teamAfterVerifyDTO.getDelMainUserMap()) ?  teamAfterVerifyDTO.getDelMainUserMap() : new HashMap<>();
        if (Objects.nonNull(addMainUserMap) && Objects.equals(UserTeamOperateTagEnum.GET_CUSTOMER.getOperateTag(), teamAfterVerifyDTO.getOperateTag())) {
            Set<String> userIdSet = addMainUserMap.values().stream().findFirst().get();
            changeUserId = new ArrayList<>(userIdSet).get(BasicConstant.ZERO);
        }

        List<Long> existTeamBatchDataIdList = new ArrayList<>();
        if (CollectionsUtil.isNotEmpty(teamBatchPojos)) {
            existTeamBatchDataIdList = teamBatchPojos.stream().map(TeamBatchPojo::getDataId).collect(Collectors.toList());
        }
        UserEntity userEntity = userModel.getByKey(changeUserId, corpid);
        if (Objects.isNull(userEntity)) {
            TeamBatchPojo teamBatchPojo = new TeamBatchPojo();
            teamBatchPojo.setCode(UserTeamErrorCodeEnum.API_ERROR_271036.getCode());
            teamBatchPojo.setFailMsg(I18nMessageUtil.getMessage(TeamMembersConstant.TEAM_MEMBER_ERROR));
            teamBatchPojo.setFailMsgReason(I18nMessageUtil.getMessage(TeamMembersConstant.USER_NOT_EXIST));
            teamBatchPojos.add(teamBatchPojo);
            return;
        }
        Map<Long, PaasFormDataEntityExt> entityExtMap = new HashMap<>(dataIdList.size());
        // 公海池规则的判断处理
        Map<Integer, List<String>> customerRuleErrorMap = new HashMap<>(BasicConstant.ONE);
        Map<Long, String> customerNameMap = getCustomerNameMap(dataIdList, corpid, entityExtMap);
        customerRuleErrorMap = listBatchService.canGainCustomer(corpid, dataIdList, userEntity, entityExtMap);
        customerRuleError(customerRuleErrorMap, teamBatchPojos, originalIdList, customerNameMap, existTeamBatchDataIdList, addMainUserMap, delMainUserMap);
        if (CollectionsUtil.isNotEmpty(teamBatchPojos)) {
            return;
        }
        if (!customerRuleErrorMap.isEmpty()) {
            (CollectionsUtil.isNotEmpty(originalIdList) ? originalIdList : new ArrayList<>()).removeAll(CollectionsUtil.isNotEmpty(dataIdList) ? dataIdList : new ArrayList<>());
            for (Long dataId : originalIdList) {
                //这些都是异常数据
                if (existTeamBatchDataIdList.contains(dataId)) {
                    continue;
                }
                String customerName = customerNameMap.get(dataId);
                TeamBatchPojo teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271026.getCode(), UserTeamErrorCodeEnum.API_ERROR_271026.getMsg(),
                        customerName, UserTeamOperateTagEnum.HANDOVER.getName());
                teamBatchPojos.add(teamBatchPojo);
            }
        }
    }

    public Map<Long,String> getCustomerNameMap(List<Long> handoverIdSet, String corpid, Map<Long, PaasFormDataEntityExt> entityExtMap) throws XbbException {
        Map<Long,String> customerNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (handoverIdSet.isEmpty()){
            return customerNameMap;
        }
        IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.DATAID.getAlias(),handoverIdSet));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, indexTypeEnum.getType()));
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(boolQueryBuilder);
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 1, handoverIdSet.size());
        SearchRequest searchRequest = new SearchRequest(indexTypeEnum.getIndex());
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest,searchRequest,PaasFormDataEntityExt.class);
        for (PaasFormDataEntityExt entity : esEntities.getContent()){
            customerNameMap.put(entity.getDataId(),entity.getData().getString(CustomerManagementEnum.NAME.getAttr()));
            entityExtMap.put(entity.getDataId(), entity);
        }
        return customerNameMap;
    }


    /**
     * 这边校验公海池最大客户数以及捞取频率，所有数据报错都是一样，所以下面有取巧动作
     *
     * @param customerRuleErrorMap
     * @param teamBatchPojos
     * @param dataIdList
     * @param customerNameMap
     * @param existTeamBatchDataIdList
     */
    private void customerRuleError(Map<Integer, List<String>> customerRuleErrorMap, List<TeamBatchPojo> teamBatchPojos, List<Long> dataIdList,
                                   Map<Long, String> customerNameMap, List<Long> existTeamBatchDataIdList, Map<String, Set<String>> addMainUserMap,
                                   Map<String, Set<String>> delMainUserMap) {

        if (customerRuleErrorMap.isEmpty()) {
            return;
        }
        for (Map.Entry<Integer, List<String>> entry : customerRuleErrorMap.entrySet()) {
            if (Objects.equals(entry.getKey(), CustomerRuleEnum.MAX_CUSTOMER_NUM_RULE.getCode())) {
                for (Long dataId : dataIdList) {
                    if (existTeamBatchDataIdList.contains(dataId)) {
                        continue;
                    }
                    String customerName = customerNameMap.get(dataId);
                    TeamBatchPojo teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271027.getCode(), UserTeamErrorCodeEnum.API_ERROR_271027.getMsg(),
                            customerName, UserTeamOperateTagEnum.HANDOVER.getName(), dataId);
                    teamBatchPojos.add(teamBatchPojo);
                    addMainUserMap.remove(String.valueOf(dataId));
                    delMainUserMap.remove(String.valueOf(dataId));
                }
                break;
            } else if (Objects.equals(entry.getKey(), CustomerRuleEnum.GAIN_RATE_RULE.getCode())) {
                for (Long dataId : dataIdList) {
                    if (existTeamBatchDataIdList.contains(dataId)) {
                        continue;
                    }
                    String customerName = customerNameMap.get(dataId);
                    TeamBatchPojo teamBatchPojo = new TeamBatchPojo(UserTeamErrorCodeEnum.API_ERROR_271028.getCode(), UserTeamErrorCodeEnum.API_ERROR_271028.getMsg(),
                            customerName, UserTeamOperateTagEnum.HANDOVER.getName(), dataId);
                    teamBatchPojos.add(teamBatchPojo);
                    addMainUserMap.remove(String.valueOf(dataId));
                    delMainUserMap.remove(String.valueOf(dataId));
                }
                break;
            }
        }
    }

    /**
     * 报错信息整合
     *
     * @param teamBatchPojo 报错信息
     * @param operateStr 操作
     */
    private void mergeFailMsg(TeamBatchPojo teamBatchPojo, String operateStr) {
        StringBuilder msg = new StringBuilder();
        msg.append(I18nMessageUtil.getMessage(ListBatchConstant.ALL_DATA));
        msg.append(operateStr).append(I18nMessageUtil.getMessage(ListBatchConstant.FAIL));
        teamBatchPojo.setFailMsg(msg.toString());
    }

    @Override
    public void afterSave(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException {
        List<Long> dataId = teamAfterVerifyDTO.getDataId();
        String corpid = teamAfterVerifyDTO.getCorpid();
        boolean customerSeniorModel = commonHelp.isCustomerPublicPoolSeniorModel(corpid);

        // 修改团队还要更新客户主数据的 分配时间 , 更新时间
        List<UpdateDataEntity> updateDataEntityArrayList = new ArrayList<>();
        //只有不是删除负责人的场景下才会更新分配时间，注意移交的时候会有删除负责人的动作，所以这个移交需要考虑进来,有问题找梦娜产品
        for (int i = 0; i < dataId.size(); i++) {
            UpdateDataEntity updateData = new UpdateDataEntity();
            Set<String> addUserSet = teamAfterVerifyDTO.getAddMainUserMap().get(String.valueOf(dataId.get(i)));
            Set<String> updateToMainUserSet = teamAfterVerifyDTO.getUpdateToMainUserMap().get(String.valueOf(dataId.get(i)));
            if (CollectionsUtil.isNotEmpty(addUserSet) || CollectionsUtil.isNotEmpty(updateToMainUserSet) || Objects.equals(UserTeamOperateTagEnum.HANDOVER.getOperateTag(), teamAfterVerifyDTO.getOperateTag())) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put(CustomerManagementEnum.DISTRIBUTION_DATE.getAttr(), DateTimeUtil.getInt());
                //此方法会更新updatetime为当前时间
                updateData = ExplainUtil.getUpdateData(dataId.get(i), jsonObject, corpid);
            }else {
                updateData.setId(dataId.get(i));
                updateData.setCorpid(corpid);
            }
            //最新的操作一定要保证更新时间最新
            updateData.setUpdateTime(DateUtil.getNow()+1);
            updateDataEntityArrayList.add(updateData);
        }
        customerModel.updateBatch(updateDataEntityArrayList, corpid, WriteRequest.RefreshPolicy.NONE);

        //添加团队成员要更新redis中的捞取频次(随老逻辑只有在负责人插入的时候更新)
        Map<String, Set<String>> addMainUserMap = teamAfterVerifyDTO.getAddMainUserMap();
        Map<String, Set<String>> delMainUserMap = teamAfterVerifyDTO.getDelMainUserMap();
        //先过滤value为null的，否则 v.getValue().stream() 空指针；后续增加逻辑，只有非捞取、分配、移交，才会走下面方法，区分的原因是因为这几个入口有批量逻辑 issue#50574,把逻辑放到他们service层处理
        if (!Objects.equals(UserTeamOperateTagEnum.GET_CUSTOMER.getOperateTag(), teamAfterVerifyDTO.getOperateTag())
        && !Objects.equals(UserTeamOperateTagEnum.DISTRIBUTION.getOperateTag(), teamAfterVerifyDTO.getOperateTag())
        && !Objects.equals(true, teamAfterVerifyDTO.getIsNew())) {
            List<String> idList = addMainUserMap.entrySet().stream()
                    .filter(v -> Objects.nonNull(v.getValue()))
                    .flatMap(v -> v.getValue().stream())
                    .distinct().collect(Collectors.toList());
            List<UserEntity> users = userModel.findEntitysByUserIds(idList, corpid);
            for (Long data: dataId) {
                Set<String> addMainUsers = addMainUserMap.getOrDefault(String.valueOf(data), new HashSet<>());
                List<UserEntity> collect = users.stream().filter(v -> addMainUsers.contains(v.getUserId())).collect(Collectors.toList());
                for (UserEntity userEntity : collect) {
                    customerRuleService.updateGainRateToRedis(corpid,userEntity);
                }
            }
        }
        if (Objects.equals(teamAfterVerifyDTO.getOperateTag(), UserTeamOperateTagEnum.HANDOVER.getOperateTag())) {
            if (Objects.nonNull(delMainUserMap)) {
                List<Long> customerIds = Optional.of(delMainUserMap.keySet()).get().stream().map(Long::valueOf).collect(Collectors.toList());
                if (customerSeniorModel){
                    transferBackRuleScriptService.deletePublicSeniorTag(corpid,customerIds,XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(),teamAfterVerifyDTO.getFormId());
                }else {
                    customerRuleService.deletePublicTag(corpid, customerIds);
                }
            }
        }
        // 后续业务 联系人 合同 退货退款 应收款 机会 报价单 预收款余额
    }

    @Override
    public void log(TeamAfterVerifyDTO teamAfterVerifyDTO) throws XbbException {
        super.log(teamAfterVerifyDTO);
    }

    /**
     * 团队详情编辑协同人权限
     *
     * @param teamDetailUpdateDTO
     * @return
     * @throws XbbException
     */
    @Override
    public TeamDetailEditCoPerVO editCoPermission(TeamDetailUpdateDTO teamDetailUpdateDTO) throws XbbException {
        TeamDetailEditCoPerVO teamDetailEditCoPerVO = new TeamDetailEditCoPerVO();
        Long dataId = teamDetailUpdateDTO.getDataId();
        String corpid = teamDetailUpdateDTO.getCorpid();
        Long id = teamDetailUpdateDTO.getId();
        //编辑协同人权限
        Integer formPermission = teamDetailUpdateDTO.getFormPermission();
        CustomerUserEntity shouldUpdateEntity = customerUserModel.getByKey(id, corpid);
        if (Objects.nonNull(shouldUpdateEntity)) {
            Integer dbFormPermission = shouldUpdateEntity.getFormPermission();
            if (Objects.isNull(dbFormPermission)) {
                dbFormPermission = FormCoUserDefaultPermissionEnum.getDefaultPerByBus(teamDetailUpdateDTO.getBusinessType());
            }
            if (!Objects.equals(formPermission, dbFormPermission)) {
                shouldUpdateEntity.setFormPermission(formPermission);
                customerUserModel.updateEditFormPer(shouldUpdateEntity);
                customerModel.updateTime(dataId,corpid);
                String content = "";
                if (Objects.equals(formPermission, CoUserPermissionEnum.EDIT.getPermissionValue())) {
                    content = I18nMessageUtil.getMessage(TeamMembersConstant.EDIT);
                }else {
                    content = I18nMessageUtil.getMessage(TeamMembersConstant.NO_EDIT);
                }
                CustomerEntityExt customerEntityExt = customerModel.getByKey(dataId, corpid);
                saveUpdateCoPerLogger(teamDetailUpdateDTO.getLoginUser(), teamDetailUpdateDTO.getFormId(), shouldUpdateEntity.getUserId(),
                        corpid, teamDetailUpdateDTO.getBusinessType(), customerEntityExt,  content, teamDetailUpdateDTO.getHttpHeader());

                TeamDynamicStrategy teamDynamicStrategy = dynamicStrategyFactory.getTeamDynamicStrategyByBusinessType(teamDetailUpdateDTO.getBusinessType());
                teamDynamicStrategy.saveUpdateCoPerDynamic(DynamicTeamUpdateDTO.initDynamicTeamUpdateDTO(teamDetailUpdateDTO,BeanUtil.copyProperties(shouldUpdateEntity,UserTeamEntity.class,true)));
            }
        }
        return teamDetailEditCoPerVO;
    }

    /**
     * 编辑团队成员标签
     *
     * @param teamDetailEditLabelDTO 编辑团队成员标签的接收实体
     * @return
     */
    @Override
    public TeamDetailEditLabelVO editLabel(TeamDetailEditLabelDTO teamDetailEditLabelDTO) throws XbbException {
        TeamDetailEditLabelVO teamDetailEditLabelVO = new TeamDetailEditLabelVO();
        String corpid = teamDetailEditLabelDTO.getCorpid();
        Long id = teamDetailEditLabelDTO.getId();
        Long dataId = teamDetailEditLabelDTO.getDataId();
        JSONArray labels = teamDetailEditLabelDTO.getLabels();
        CustomerUserEntity customerUserEntity = customerUserModel.getByKey(id, corpid);
        JSONArray dbLabels = customerUserEntity.getLabels();
        List<Long> lbIdFormList = new ArrayList<>();
        List<Long> lbIdSysList = new ArrayList<>();
        List<Long> dbLbIdFormList = new ArrayList<>();
        List<Long> dbLbIdSysList = new ArrayList<>();
        boolean addTag = userTeamHelp.getAddLogTag(labels, dbLabels, lbIdFormList, lbIdSysList, dbLbIdFormList, dbLbIdSysList);
        if (addTag) {
            customerUserEntity.setLabels(labels);
            customerUserModel.editLabel(customerUserEntity);
            //更新主业务的更新时间
            customerModel.updateTime(dataId,corpid);
            CustomerEntityExt customerEntityExt = customerModel.getByKey(dataId, corpid);
            //记录日志信息
            saveUpdateLabelLogger(teamDetailEditLabelDTO.getLoginUser(), teamDetailEditLabelDTO.getFormId(), customerUserEntity.getUserId(), corpid,
                    teamDetailEditLabelDTO.getBusinessType(), customerEntityExt, customerUserEntity.getIsMain(), teamDetailEditLabelDTO.getHttpHeader(),
                    lbIdFormList, lbIdSysList, dbLbIdFormList, dbLbIdSysList, customerUserEntity.getUpdateTime());

            TeamDynamicStrategy teamDynamicStrategy = dynamicStrategyFactory.getTeamDynamicStrategyByBusinessType(teamDetailEditLabelDTO.getBusinessType());
            teamDynamicStrategy.saveUpdateLabelDynamic(DynamicTeamLabelDTO.initDynamicTeamLabelDTO(teamDetailEditLabelDTO, BeanUtil.copyProperties(customerUserEntity, UserTeamEntity.class, true)));
        }
        return teamDetailEditLabelVO;
    }

}
